package com.meiyu.live.ui.mine;

import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Response;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.meiyu.live.BaseFragment;
import com.meiyu.live.R;
import com.meiyu.live.comm.UserConfig;
import com.meiyu.live.eventbus.FocusEvent;
import com.meiyu.live.eventbus.LoginEvent;
import com.meiyu.live.eventbus.UserInfoUpdateEvent;
import com.meiyu.live.net.param.PersonalParams;
import com.meiyu.live.net.response.PersonalResponse;
import com.meiyu.live.popj.ActiveInfo;
import com.meiyu.live.popj.PersonalInfo;
import com.meiyu.live.popj.RelationInfo;
import com.meiyu.live.ui.login.LoginActivity;
import com.meiyu.live.util.ImageUtil;
import com.meiyu.live.util.RippleUtils;

import de.greenrobot.event.EventBus;

public class MineFragment extends BaseFragment implements View.OnClickListener {

    private View btn_message, btn_edit;
    private View layout_follow, layout_fans, layout_mytv, layout_vip;
    private TextView tv_follow_count, tv_fans_count, tv_mytv_count, tv_mylevel, tv_level;
    private View layout_fans_contribution, layout_my_contribution, layout_mymoney, layout_recharge, layout_settings, layout_advice,layout_about,layout_policy;
    private ImageView iv_avatar, iv_avatar_blur, iv_sex;
    private TextView tv_account, tv_nickname, tv_signature;
    ListView lv_event;

    private ImageLoader imageLoader;
    private DisplayImageOptions options;
    private Bitmap bitmapAvatarBlur;

    public MineFragment() {
    }

    public static MineFragment newInstance() {
        MineFragment fragment = new MineFragment();
        return fragment;
    }

    @Override
    protected void init() {
        imageLoader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.icon_def_header)          // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.icon_def_header)  // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.icon_def_header)       // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)                          // 设置下载的图片是否缓存在SD卡中
                .build();
        int mainColor = getActivity().getResources().getColor(R.color.main_theme_color);

        btn_message = findViewById(R.id.btn_message);
        btn_message.setOnClickListener(this);
        btn_edit = findViewById(R.id.btn_edit);
        btn_edit.setOnClickListener(this);

        iv_avatar = (ImageView) findViewById(R.id.iv_avatar);
        iv_sex = (ImageView) findViewById(R.id.iv_sex);
        iv_avatar.setOnClickListener(this);
        iv_avatar_blur = (ImageView) findViewById(R.id.iv_avatar_blur);

        tv_account = (TextView) findViewById(R.id.tv_account);
        tv_nickname = (TextView) findViewById(R.id.tv_nickname);
        tv_signature = (TextView) findViewById(R.id.tv_signature);

        layout_follow = findViewById(R.id.layout_follow);
        layout_follow.setOnClickListener(this);
        layout_fans = findViewById(R.id.layout_fans);
        layout_fans.setOnClickListener(this);
        layout_mytv = findViewById(R.id.layout_mytv);
        layout_mytv.setOnClickListener(this);
        layout_vip = findViewById(R.id.layout_vip);
        layout_vip.setOnClickListener(this);
        lv_event = (ListView) findViewById(R.id.lv_event);
        lv_event.setOnItemClickListener(onItemClickListener);
        lv_event.setAdapter(new EventAdapter());
        RippleUtils.setRippleDrawable(layout_follow, mainColor);
        RippleUtils.setRippleDrawable(layout_fans, mainColor);
        RippleUtils.setRippleDrawable(layout_mytv, mainColor);
        RippleUtils.setRippleDrawable(layout_vip, mainColor);
        tv_follow_count = (TextView) findViewById(R.id.tv_follow_count);
        tv_fans_count = (TextView) findViewById(R.id.tv_fans_count);
        tv_mytv_count = (TextView) findViewById(R.id.tv_mytv_count);
        tv_mylevel = (TextView) findViewById(R.id.tv_mylevel);
        tv_level = (TextView) findViewById(R.id.tv_level);

        layout_fans_contribution = findViewById(R.id.layout_fans_contribution);
        layout_fans_contribution.setOnClickListener(this);
        layout_my_contribution = findViewById(R.id.layout_my_contribution);
        layout_my_contribution.setOnClickListener(this);

        layout_mymoney = findViewById(R.id.layout_mymoney);
        layout_mymoney.setOnClickListener(this);
        layout_recharge = findViewById(R.id.layout_recharge);
        layout_recharge.setOnClickListener(this);

        layout_settings = findViewById(R.id.layout_settings);
        layout_settings.setOnClickListener(this);
        layout_advice = findViewById(R.id.layout_advice);
        layout_advice.setOnClickListener(this);
        layout_about = findViewById(R.id.layout_about);
        layout_about.setOnClickListener(this);
        layout_policy = findViewById(R.id.layout_policy);
        layout_policy.setOnClickListener(this);

        RippleUtils.setRippleDrawable(layout_fans_contribution, mainColor);
        RippleUtils.setRippleDrawable(layout_my_contribution, mainColor);
        RippleUtils.setRippleDrawable(layout_mymoney, mainColor);
        RippleUtils.setRippleDrawable(layout_recharge, mainColor);
        RippleUtils.setRippleDrawable(layout_settings, mainColor);
        RippleUtils.setRippleDrawable(layout_advice, mainColor);
        RippleUtils.setRippleDrawable(layout_about, mainColor);
        RippleUtils.setRippleDrawable(layout_policy, mainColor);

        updatePersonalInfo();
        getData();
    }

    AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            EventActivity.start(getActivity(), UserConfig.getInstance().getActiveInfos().get(position));
        }
    };

    @Override
    public int getContextView() {
        return R.layout.fragment_mine;
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
        if (bitmapAvatarBlur != null && !bitmapAvatarBlur.isRecycled()) {
            bitmapAvatarBlur.recycle();
        }
        bitmapAvatarBlur = null;
    }

    @Override
    public void onClick(View view) {
        if (!UserConfig.getInstance().isLogin() && view != layout_settings) {
            startActivity(LoginActivity.class);
        } else if (view == btn_edit) {
            startActivity(UserInfoActivity.class);
        } else if (view == btn_message) {
            startActivity(MessageActivity.class);
        } else if (view == iv_avatar) {
        } else if (view == layout_follow) {
            startActivity(MyFollowActivity.class);
        } else if (view == layout_fans) {
            startActivity(MyFansActivity.class);
        } else if (view == layout_mytv) {
            startActivity(MyTvActivity.class);
        } else if (view == layout_vip) {
            startActivity(MyLevelActivity.class);
        } else if (view == layout_fans_contribution) {
            startActivity(FansContributionActivity.class);
        } else if (view == layout_my_contribution) {
            startActivity(FansContributionActivity.class);
        } else if (view == layout_mymoney) {
            startActivity(MyCoinsActivity.class);
        } else if (view == layout_recharge) {
            startActivity(RechargeActivity.class);
        } else if (view == layout_settings) {
            startActivity(SettingsActivity.class);
        } else if (view == layout_advice) {
            startActivity(AdviceActivity.class);
        } else if (view == layout_about) {
            startActivity(AboutActivity.class);
        } else if (view == layout_policy) {
            startActivity(PolicyActivity.class);
        }
    }

    private class EventAdapter extends BaseAdapter {

        private class ViewHolder {
            TextView tv_name;
        }

        @Override
        public int getCount() {
            return UserConfig.getInstance().getPersonalInfo() != null && UserConfig.getInstance().getActiveInfos() != null ? UserConfig.getInstance().getActiveInfos().size() : 0;
        }

        @Override
        public Object getItem(int position) {
            return UserConfig.getInstance().getActiveInfos().get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = getInflater().inflate(R.layout.adapter_event, null);
                holder = new ViewHolder();
                holder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            final ActiveInfo bean = UserConfig.getInstance().getActiveInfos().get(position);
            holder.tv_name.setText(bean.getName());
            return convertView;
        }
    }

    private void updatePersonalInfo() {
        final PersonalInfo personalInfo = UserConfig.getInstance().getPersonalInfo();
        if (personalInfo != null) {
            imageLoader.displayImage(personalInfo.getAvatar(), iv_avatar, options, new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String s, View view) {

                }

                @Override
                public void onLoadingFailed(String s, View view, FailReason failReason) {

                }

                @Override
                public void onLoadingComplete(String s, View view, final Bitmap bitmap) {
                    if (bitmap != null) {
                        if (Build.VERSION.SDK_INT >= 17) {
                            if (bitmapAvatarBlur != null && !bitmapAvatarBlur.isRecycled()) {
                                bitmapAvatarBlur.recycle();
                                iv_avatar_blur.setImageResource(R.color.main_theme_color);
                            }
                            try {
                                bitmapAvatarBlur = ImageUtil.blurBitmap(getActivity(), bitmap);
                                iv_avatar_blur.setImageBitmap(bitmapAvatarBlur);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            if (bitmapAvatarBlur != null && !bitmapAvatarBlur.isRecycled()) {
                                bitmapAvatarBlur.recycle();
                                iv_avatar_blur.setImageResource(R.color.main_theme_color);
                            }
                            new Thread() {
                                @Override
                                public void run() {
                                    bitmapAvatarBlur = ImageUtil.blurBitmapOld(getActivity(), bitmap);
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            iv_avatar_blur.setImageBitmap(bitmapAvatarBlur);
                                        }
                                    });
                                }
                            }.start();
                        }
                    }
                }

                @Override
                public void onLoadingCancelled(String s, View view) {

                }
            });
            int sexRes;
            switch (personalInfo.getSex()) {
                case "m":
                    sexRes = R.drawable.ic_sex_male;
                    break;
                case "f":
                    sexRes = R.drawable.ic_sex_female;
                    break;
                default:
                    sexRes = R.drawable.ic_sex_secret;
                    break;
            }
            iv_sex.setImageResource(sexRes);
            if (UserConfig.getInstance().getRelationInfo() != null) {
                tv_level.setText(UserConfig.getInstance().getRelationInfo().getLevel() + "");
            }
            tv_nickname.setText("昵称:" + personalInfo.getName());
            tv_account.setText("账号:" + personalInfo.getCuteCode());
            tv_signature.setText("个性签名:" + personalInfo.getSignature());

        } else {
            iv_avatar.setImageResource(R.drawable.icon_def_header);
            iv_avatar_blur.setImageResource(R.color.main_theme_color);
            tv_account.setText("点击头像登录");
            tv_nickname.setText("");
            tv_signature.setText("");
            tv_level.setVisibility(View.GONE);
            iv_sex.setVisibility(View.GONE);
            if (bitmapAvatarBlur != null && !bitmapAvatarBlur.isRecycled()) {
                bitmapAvatarBlur.recycle();
            }
            bitmapAvatarBlur = null;
        }

        final RelationInfo relationInfo = UserConfig.getInstance().getRelationInfo();
        if (relationInfo != null) {
            tv_mylevel.setText(relationInfo.getLevel() + "级");
            tv_follow_count.setText(relationInfo.getFocus() + "人");
            tv_fans_count.setText(relationInfo.getFans() + "人");
            tv_mytv_count.setText(relationInfo.getMyHookUpCount() + "个");
        } else {
            tv_mylevel.setText("0级");
            tv_follow_count.setText("0人");
            tv_fans_count.setText("0人");
            tv_mytv_count.setText("0个");
        }

        setListViewHeightBasedOnChildren(lv_event);
    }

    private void getData() {
        if (UserConfig.getInstance().isLogin()) {
            request(new PersonalParams(null), PersonalResponse.class, new Response.Listener<PersonalResponse>() {
                @Override
                public void onResponse(PersonalResponse personalResponse) {
                    if (personalResponse != null) {
                        UserConfig.getInstance().setPersonalInfo(personalResponse.getPrivateInfo());
                        UserConfig.getInstance().setRelationInfo(personalResponse.getRelationinfo());
                        UserConfig.getInstance().setActiveInfos(personalResponse.getActiveInfo());
                        updatePersonalInfo();
                    }
                }
            });
        }

    }

    public void onEvent(LoginEvent event) {
        if (event.isLogin) {
            getData();
        } else {
            updatePersonalInfo();
        }
    }

    public void onEvent(UserInfoUpdateEvent event) {
        getData();
    }

    public void onEvent(FocusEvent event) {
        RelationInfo relationInfo = UserConfig.getInstance().getRelationInfo();
        if (event.isFocus) {
            relationInfo.setFocus(relationInfo.getFocus() + 1);
            updatePersonalInfo();
        } else {
            relationInfo.setFocus(relationInfo.getFocus() - 1);
            updatePersonalInfo();
        }
    }
}
